#include "SingletonLhan.h"
#include <QDebug>

#include "UI/ModRun/Output/FactoryOutput.h"

//初始化;
std::shared_ptr<SingletonLhan> SingletonLhan::m_pInstance;

std::mutex SingletonLhan::m_pMtx;

//私有化构造;
SingletonLhan::SingletonLhan()
{
    //防破解;
    if (m_pInstance)
    {
        throw std::runtime_error("已经实例化，不能再创建");
    }
    QString strOutput = "单例模式:懒汉:构造";
    qDebug() << strOutput;
    std::shared_ptr<IOutput> pOutPut = FactoryOutput::GetInstance()->CreateRunOutput();
    if (pOutPut)
    {
        std::initializer_list<QString> outList{ strOutput };
        pOutPut->OutPut(outList);
    }
}


SingletonLhan::~SingletonLhan()
{
    QString strOutput = "单例模式:懒汉:析构";
    qDebug() << strOutput;
    std::shared_ptr<IOutput> pOutPut = FactoryOutput::GetInstance()->CreateRunOutput();
    if (pOutPut)
    {
        std::initializer_list<QString> outList{ strOutput };
        pOutPut->OutPut(outList);
    }
}

//获取实例;
std::shared_ptr<SingletonLhan> SingletonLhan::GetInstance()
{
    //双重检查锁;此处涉及原子操作，双重检查锁也是不安全的，见C++11版本实现;
    if (!m_pInstance)
    {
        //互斥;
        std::lock_guard<std::mutex> guardMutex(m_pMtx);
        if (!m_pInstance)
        {
            m_pInstance.reset(new SingletonLhan());
        }
    }
    return m_pInstance;
}

//测试函数;
void SingletonLhan::Display()
{
    QString strThis = QString::number(reinterpret_cast<quintptr>(this), 16);
    QString strOutput = "单例模式:懒汉:Display " + strThis;
    qDebug() << strOutput;
    std::shared_ptr<IOutput> pOutPut = FactoryOutput::GetInstance()->CreateRunOutput();
    if (pOutPut)
    {
        std::initializer_list<QString> outList{ strOutput };
        pOutPut->OutPut(outList);
    }
}
